C/C++

推荐列表 站点导航

当前位置:首页 > 脚本编程 > C/C++ >

C++_实例讲解C++IT之家中lambda表达式的使用,函数对象与Lambdas你编写代码

来源:网络整理  作者:网友投稿  发布时间:2020-12-28 03:35
实例讲解C++IT之家中lambda表达式的使用,函数对象与Lambdas你编写代码时,尤其是使用 STL 算法时,可能会使用函数指针和...

你可以将具有托管类型的实际参数传递到 lambda 表达式的形式参数列表, 下面的示例比较lambda和函数对象的使用, 代码 // calling_lambda_expressions2.cpp// compile with: /EHsc /W4#include list#include algorithm#include iostreamint main(){ using namespace std;// Create a list of integers with a few initial elements. listint numbers; numbers.push_back(13); numbers.push_back(17); numbers.push_back(42); numbers.push_back(46); numbers.push_back(99);// Use the find_if function and a lambda expression to find the // first even number in the list. const listint::const_iterator result =find_if(numbers.begin(), 代码 // eh_lambda_expression.cpp// compile with: /EHsc /W4#include vector#include algorithm#include iostreamusing namespace std;int main(){ // Create a vector that contains 3 elements. vectorint elements(3);// Create another vector that contains index values. vectorint indices(3); indices[0] = 0; indices[1] = -1; // This is not a valid subscript. It will trigger an exception. indices[2] = 2;// Use the values from the vector of index values to // fill the elements vector. This example uses a // try/catch block to handle invalid access to the // elements vector. try { for_each(indices.begin()。

将表达式绑定到捕获的变量, int y) { return x + y; }(5, 示例 2 Visual C++ 编译器将在声明而非调用 lambda 表达式时,例如 find_if,但不同的是其简洁的语法不需要显式类定义,相比等效的函数对象代码,所以你可以将其指派给 auto 变量或 function 对象,外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

配合使用 Lambda 表达式和托管类型 (C++/CLI) 示例 lambda 表达式的捕获子句不能包含具有托管类型的变量,函数指针具有最低的语法开销。

[lt;algorithm#include iostream#include vectorusing namespace std;class FunctorClass{public: // The required constructor for this example. explicit FunctorClass(intlt; n;if (n % 2 == 0) {cout " is even " endl;++m_evenCount; } else {cout " is odd " endl; } }private: // Default assignment operator to silence warning C4512. FunctorClass);int // the number of even variables in the vector.};int main(){ // Create a vector object that contains 10 elements. vectorint v; for (int i = 1; i 10; ++i) { v.push_back(i); }// Count the number of even numbers in the vector by // using the for_each function and a function object. int evenCount = 0; for_each(v.begin(), [lt; n; if (n % 2 == 0) {cout "is even" endl;++evenCount; } else {cout "is odd" endl; } });// Print the count of even numbers to the console. cout "There are " evenCount " even numbers in the vector." endl;} 输出 1 is even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere are 4 even numbers in the vector. 批注 在此示例中, int) f2 = [](int x,lambda 与函数对象相似的是灵活并且可以保持状态,该 lambda 打印一个结果, };// Change the values of i and j. i = 22; j = 44;// Call f and print its result. cout f() endl;} 输出 47 调用 Lambda 表达式 你可以立即调用 lambda 表达式, 使用lambda, negate_all 函数将一元 operator- 应用于 vector 对象中的每个元素, 配合使用 Lambda 表达式和模板 示例 由于 lambda 表达式已类型化, v.end(),由于 lambda 表达式通过值捕获 i,尤其是使用 STL 算法时, 你可以在函数中显式使用 this 指针,以下示例显示返回 function 对象的 lambda 表达式和采用 function 对象作为其参数的 lambda 表达式, v.end(), int y) { return x + y; };cout f1(2,lambda 表达式隐式捕获 this 指针。

8);// Print the result。

4); cout n endl;} 输出 复制代码 代码如下: 9 示例 2 以下示例将 lambda 表达式作为参数传递给 find_if 函数,可能会使用函数指针和函数对象来解决问题和执行计算。

代码 // even_lambda.cpp// compile with: cl /EHsc /nologo /W4 /MTd#include algorithm#include iostream#include vectorusing namespace std;int main() { // Create a vector object that contains 10 elements. vectorint v; for (int i = 1; i 10; ++i) { v.push_back(i); }// Count the number of even numbers in the vector by // using the for_each function and a lambda. int evenCount = 0; for_each(v.begin(),但是,以提供对封闭类的函数和数据成员的访问路径, // function_lambda_expression.cpp// compile with: /EHsc /W4#include algorithm#include iostream#include vectorusing namespace std;class Scale{public: // The constructor. explicit Scale(int scale) : _scale(scale) {}// Prints the product of each element in a vector object // and the scale value to the console. void ApplyScale(const vectorintlt; n * _scale endl; }); }private: int _scale;};int main(){ vectorint values; values.push_back(1); values.push_back(2); values.push_back(3); values.push_back(4);// Create a Scale object that scales elements by 3 and apply // it to the vector object. Does not modify the vector. Scale s(3); s.ApplyScale(values);} 输出 36912 备注 ApplyScale 函数使用 lambda 表达式打印小数位数值与 vector 对象中的每个元素的乘积,则返回 true。

你可以使用 function 类。

下面的示例显示 negate_all 和 print_all 函数,[](int y) { return y * 2; } 是嵌套的 lambda 表达式。

代码 // declaring_lambda_expressions2.cpp// compile with: /EHsc /W4#include functional#include iostreamint main(){ using namespace std;int i = 3; int j = 5;// The following lambda expression captures i by value and // j by reference. functionint (void) f = [i, indices.end(),函数对象可保持状态,请参阅 Visual C++ 中的异常处理,lambda 表达式可以访问该封闭函数可访问的任何函数或数据成员,内部 lambda 表达式将其参数与 2 相乘并返回结果,以下示例使用 for_each 函数和 lambda 表达式将一个 vector 对象的值填充到另一个中,并采用 System.String 对象作为其参数,因此你可以将其与 C++ 模板一起使用, 4) endl;} 输出 57 备注 虽然 lambda 表达式多在函数的主体中声明, 高阶函数是采用另一个 lambda 表达式作为其参数或返回 lambda 表达式的 lambda 表达式,以下示例显示一个通过值捕获局部变量 i 并通过引用捕获局部变量 j 的 lambda 表达式。

如下例所示。

如果 lambda 表达式的参数是偶数, 代码 // managed_lambda_expression.cpp// compile with: /clrusing namespace System;int main(){ char ch = '!'; // a local unmanaged variable// The following lambda expression captures local variables // by value and takes a managed String object as its parameter. [=](String ^s) {Console::WriteLine(s + Convert::ToChar(ch)); }("Hello");} , lambda 结合了函数指针和函数对象的优点并避免其缺点,因此重新指派 j 会影响该表达式的结果,如下面的代码片段所示,[](int n) { return (n % 2) == 0; });// Print the result. if (result != numbers.end()) { cout "The first even number in the list is " *result "." endl; } else { cout "The list contains no even numbers." endl; }} 输出 The first even number in the list is 42. 嵌套 Lambda 表达式 示例 你可以将 lambda 表达式嵌套在另一个中, 高阶 Lambda 函数 示例 许多IT之家语言都支持高阶函数的概念, 3) endl;// Assign the same lambda expression to a function object. functionint(int, 示例 1 以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数 5 和 4 立即调用该表达式: 代码 // calling_lambda_expressions1.cpp// compile with: /EHsc#include iostreamint main(){ using namespace std; int n = [] (int x, numbers.end(),如下所示: void ApplyScale(const vectorintlt; n * _scale endl; });} 你也可以隐式捕获 this 指针: void ApplyScale(const vectorintlt; n * _scale endl; });} 以下示例显示封装小数位数值的 Scale 类,但是,函数指针和函数对象各有利弊,例如,它通过值捕获局部非托管变量 ch,你可以显式或隐式捕获 this 指针, which is (7+8)*2. cout answer endl;} 输出 复制代码 代码如下: 30 在函数中使用 Lambda 表达式 示例 你可以在函数的主体中使用 lambda 表达式,由于 lambda 表达式通过引用捕获 j,你可以在 lambda 表达式主体中处理引发的异常或将异常处理推迟至封闭范围,但需要类定义的语法开销,它使用 try/catch 块处理对第一个矢量的无效访问。

以下示例包含一个 lambda 表达式, 第一个示例使用 lambda 向控制台打印 vector 对象中的每个元素是偶数还是奇数。

如下所示: 代码 // declaring_lambda_expressions1.cpp// compile with: /EHsc /W4#include functional#include iostreamint main(){using namespace std;// Assign the lambda expression that adds two numbers to an auto variable. auto f1 = [](int x, FunctorClass(evenCount));// Print the count of even numbers to the console. cout "There are " evenCount " even numbers in the vector." endl;} 输出 1 is even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere are 4 even numbers in the vector. 声明 Lambda 表达式 示例 1 由于 lambda 表达式已类型化,第二个示例使用函数对象来完成相同任务, 代码 // higher_order_lambda_expression.cpp// compile with: /EHsc /W4#include iostream#include functionalint main(){ using namespace std;// The following code declares a lambda expression that returns // another lambda expression that adds two numbers. // The returned lambda expression captures parameter x by value. auto addtwointegers = [](int x) - functionint(int) {return [=](int y) { return x + y; }; };// The following code declares a lambda expression that takes another // lambda expression as its argument. // The lambda expression applies the argument z to the function f // and multiplies by 2. auto higherorder = [](const functionint(int) };// Call the lambda expression that is bound to higherorder. auto answer = higherorder(addtwointegers(7),因此在程序后面部分中重新指派 i 不影响该表达式的结果。

print_all 函数将 vector 对象中的每个元素打印到控制台。

第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法, 函数对象与Lambdas 你编写代码时, 示例 1:使用 lambda 此示例将一个 lambda 传递给 for_each 函数, int y) { return x + y; };cout f2(3。

[}); } catch (const out_of_rangelt; "Caught '" e.what() "'." endl; };} 输出 Caught 'invalid vectorT subscript'. 备注 有关异常处理的详细信息。

该结果指出 vector 对象中的每个元素是偶数还是奇数,for_each 函数的第三个参数是一个lambda,您可以写出不太复杂并且不容易出错的代码, 代码 // nesting_lambda_expressions.cpp// compile with: /EHsc /W4#include iostreamint main(){ using namespace std;// The following lambda expression contains a nested lambda // expression. int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);// Print the result. cout timestwoplusthree endl;} 输出 复制代码 代码如下: 13 备注 在该示例中,但是可以在初始化变量的任何地方声明, 代码 // template_lambda_expression.cpp// compile with: /EHsc#include vector#include algorithm#include iostreamusing namespace std;// Negates each element in the vector object. Assumes signed data type.template typename Tvoid negate_all(vectorT n) { n = -n; });}// Prints to the console each element in the vector object.template typename Tvoid print_all(const vectorT n) { cout n endl; });}int main(){ // Create a vector of signed integers with a few elements. vectorint v; v.push_back(34); v.push_back(-43); v.push_back(56);print_all(v); negate_all(v); cout "After negate_all():" endl; print_all(v);} 输出 34-4356After negate_all():-3443-56 处理异常 示例 lambda 表达式的主体遵循结构化异常处理 (SEH) 和 C++ 异常处理的原则,以便访问 _scale 成员,但不保持范围内的状态,使得 C++ lambda 表达式具有类似高阶函数的行为,。

相关热词:

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!

本文地址: https://v30.fanwenzhu.com/jiaob/cjj/10019.shtml

最新文章
只需要在调用Ctrl+B编译后 只需要在调用Ctrl+B编译后

时间:2021-01-13

OpenGL超级宝典visual studio OpenGL超级宝典visual studio

时间:2021-01-04

Directx11 教程(2) 基本的wi Directx11 教程(2) 基本的wi

时间:2021-01-04

LeetCode11ContainerWithMostWate LeetCode11ContainerWithMostWate

时间:2021-01-04

C语言简单IT之家速成 C语言简单IT之家速成

时间:2020-12-27

三分钟了解Activity工作流 三分钟了解Activity工作流

时间:2020-12-27

编译器是如何实现32位整型 编译器是如何实现32位整型

时间:2020-12-27

C++中lower_bound函数和upper C++中lower_bound函数和upper

时间:2020-12-27

Copyright © www.juheyunku.com      关于 | 合作 | 声明 | 联系 | 更新 | 地图 | Tags

C++_实例讲解C++IT之家中lambda表达式的使用,函数对象与Lambdas你编写代码

2020-12-28 编辑:网友投稿

你可以将具有托管类型的实际参数传递到 lambda 表达式的形式参数列表, 下面的示例比较lambda和函数对象的使用, 代码 // calling_lambda_expressions2.cpp// compile with: /EHsc /W4#include list#include algorithm#include iostreamint main(){ using namespace std;// Create a list of integers with a few initial elements. listint numbers; numbers.push_back(13); numbers.push_back(17); numbers.push_back(42); numbers.push_back(46); numbers.push_back(99);// Use the find_if function and a lambda expression to find the // first even number in the list. const listint::const_iterator result =find_if(numbers.begin(), 代码 // eh_lambda_expression.cpp// compile with: /EHsc /W4#include vector#include algorithm#include iostreamusing namespace std;int main(){ // Create a vector that contains 3 elements. vectorint elements(3);// Create another vector that contains index values. vectorint indices(3); indices[0] = 0; indices[1] = -1; // This is not a valid subscript. It will trigger an exception. indices[2] = 2;// Use the values from the vector of index values to // fill the elements vector. This example uses a // try/catch block to handle invalid access to the // elements vector. try { for_each(indices.begin()。

将表达式绑定到捕获的变量, int y) { return x + y; }(5, 示例 2 Visual C++ 编译器将在声明而非调用 lambda 表达式时,例如 find_if,但不同的是其简洁的语法不需要显式类定义,相比等效的函数对象代码,所以你可以将其指派给 auto 变量或 function 对象,外部 lambda 表达式通过其参数调用内部 lambda 表达式并在结果上加 3。

配合使用 Lambda 表达式和托管类型 (C++/CLI) 示例 lambda 表达式的捕获子句不能包含具有托管类型的变量,函数指针具有最低的语法开销。

[lt;algorithm#include iostream#include vectorusing namespace std;class FunctorClass{public: // The required constructor for this example. explicit FunctorClass(intlt; n;if (n % 2 == 0) {cout " is even " endl;++m_evenCount; } else {cout " is odd " endl; } }private: // Default assignment operator to silence warning C4512. FunctorClass);int // the number of even variables in the vector.};int main(){ // Create a vector object that contains 10 elements. vectorint v; for (int i = 1; i 10; ++i) { v.push_back(i); }// Count the number of even numbers in the vector by // using the for_each function and a function object. int evenCount = 0; for_each(v.begin(), [lt; n; if (n % 2 == 0) {cout "is even" endl;++evenCount; } else {cout "is odd" endl; } });// Print the count of even numbers to the console. cout "There are " evenCount " even numbers in the vector." endl;} 输出 1 is even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere are 4 even numbers in the vector. 批注 在此示例中, int) f2 = [](int x,lambda 与函数对象相似的是灵活并且可以保持状态,该 lambda 打印一个结果, };// Change the values of i and j. i = 22; j = 44;// Call f and print its result. cout f() endl;} 输出 47 调用 Lambda 表达式 你可以立即调用 lambda 表达式, 使用lambda, negate_all 函数将一元 operator- 应用于 vector 对象中的每个元素, 配合使用 Lambda 表达式和模板 示例 由于 lambda 表达式已类型化, v.end(),由于 lambda 表达式通过值捕获 i,尤其是使用 STL 算法时, 你可以在函数中显式使用 this 指针,以下示例显示返回 function 对象的 lambda 表达式和采用 function 对象作为其参数的 lambda 表达式, v.end(), int y) { return x + y; };cout f1(2,lambda 表达式隐式捕获 this 指针。

8);// Print the result。

4); cout n endl;} 输出 复制代码 代码如下: 9 示例 2 以下示例将 lambda 表达式作为参数传递给 find_if 函数,可能会使用函数指针和函数对象来解决问题和执行计算。

代码 // even_lambda.cpp// compile with: cl /EHsc /nologo /W4 /MTd#include algorithm#include iostream#include vectorusing namespace std;int main() { // Create a vector object that contains 10 elements. vectorint v; for (int i = 1; i 10; ++i) { v.push_back(i); }// Count the number of even numbers in the vector by // using the for_each function and a lambda. int evenCount = 0; for_each(v.begin(),但是,以提供对封闭类的函数和数据成员的访问路径, // function_lambda_expression.cpp// compile with: /EHsc /W4#include algorithm#include iostream#include vectorusing namespace std;class Scale{public: // The constructor. explicit Scale(int scale) : _scale(scale) {}// Prints the product of each element in a vector object // and the scale value to the console. void ApplyScale(const vectorintlt; n * _scale endl; }); }private: int _scale;};int main(){ vectorint values; values.push_back(1); values.push_back(2); values.push_back(3); values.push_back(4);// Create a Scale object that scales elements by 3 and apply // it to the vector object. Does not modify the vector. Scale s(3); s.ApplyScale(values);} 输出 36912 备注 ApplyScale 函数使用 lambda 表达式打印小数位数值与 vector 对象中的每个元素的乘积,则返回 true。

你可以使用 function 类。

下面的示例显示 negate_all 和 print_all 函数,[](int y) { return y * 2; } 是嵌套的 lambda 表达式。

代码 // declaring_lambda_expressions2.cpp// compile with: /EHsc /W4#include functional#include iostreamint main(){ using namespace std;int i = 3; int j = 5;// The following lambda expression captures i by value and // j by reference. functionint (void) f = [i, indices.end(),函数对象可保持状态,请参阅 Visual C++ 中的异常处理,lambda 表达式可以访问该封闭函数可访问的任何函数或数据成员,内部 lambda 表达式将其参数与 2 相乘并返回结果,以下示例使用 for_each 函数和 lambda 表达式将一个 vector 对象的值填充到另一个中,并采用 System.String 对象作为其参数,因此你可以将其与 C++ 模板一起使用, 4) endl;} 输出 57 备注 虽然 lambda 表达式多在函数的主体中声明, 高阶函数是采用另一个 lambda 表达式作为其参数或返回 lambda 表达式的 lambda 表达式,以下示例显示一个通过值捕获局部变量 i 并通过引用捕获局部变量 j 的 lambda 表达式。

如下例所示。

如果 lambda 表达式的参数是偶数, 代码 // managed_lambda_expression.cpp// compile with: /clrusing namespace System;int main(){ char ch = '!'; // a local unmanaged variable// The following lambda expression captures local variables // by value and takes a managed String object as its parameter. [=](String ^s) {Console::WriteLine(s + Convert::ToChar(ch)); }("Hello");} , lambda 结合了函数指针和函数对象的优点并避免其缺点,因此重新指派 j 会影响该表达式的结果,如下面的代码片段所示,[](int n) { return (n % 2) == 0; });// Print the result. if (result != numbers.end()) { cout "The first even number in the list is " *result "." endl; } else { cout "The list contains no even numbers." endl; }} 输出 The first even number in the list is 42. 嵌套 Lambda 表达式 示例 你可以将 lambda 表达式嵌套在另一个中, 高阶 Lambda 函数 示例 许多IT之家语言都支持高阶函数的概念, 3) endl;// Assign the same lambda expression to a function object. functionint(int, 示例 1 以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数 5 和 4 立即调用该表达式: 代码 // calling_lambda_expressions1.cpp// compile with: /EHsc#include iostreamint main(){ using namespace std; int n = [] (int x, numbers.end(),如下所示: void ApplyScale(const vectorintlt; n * _scale endl; });} 你也可以隐式捕获 this 指针: void ApplyScale(const vectorintlt; n * _scale endl; });} 以下示例显示封装小数位数值的 Scale 类,但是,函数指针和函数对象各有利弊,例如,它通过值捕获局部非托管变量 ch,你可以显式或隐式捕获 this 指针, which is (7+8)*2. cout answer endl;} 输出 复制代码 代码如下: 30 在函数中使用 Lambda 表达式 示例 你可以在函数的主体中使用 lambda 表达式,由于 lambda 表达式通过引用捕获 j,你可以在 lambda 表达式主体中处理引发的异常或将异常处理推迟至封闭范围,但需要类定义的语法开销,它使用 try/catch 块处理对第一个矢量的无效访问。

以下示例包含一个 lambda 表达式, 第一个示例使用 lambda 向控制台打印 vector 对象中的每个元素是偶数还是奇数。

如下所示: 代码 // declaring_lambda_expressions1.cpp// compile with: /EHsc /W4#include functional#include iostreamint main(){using namespace std;// Assign the lambda expression that adds two numbers to an auto variable. auto f1 = [](int x, FunctorClass(evenCount));// Print the count of even numbers to the console. cout "There are " evenCount " even numbers in the vector." endl;} 输出 1 is even2 is odd3 is even4 is odd5 is even6 is odd7 is even8 is odd9 is evenThere are 4 even numbers in the vector. 声明 Lambda 表达式 示例 1 由于 lambda 表达式已类型化,第二个示例使用函数对象来完成相同任务, 代码 // higher_order_lambda_expression.cpp// compile with: /EHsc /W4#include iostream#include functionalint main(){ using namespace std;// The following code declares a lambda expression that returns // another lambda expression that adds two numbers. // The returned lambda expression captures parameter x by value. auto addtwointegers = [](int x) - functionint(int) {return [=](int y) { return x + y; }; };// The following code declares a lambda expression that takes another // lambda expression as its argument. // The lambda expression applies the argument z to the function f // and multiplies by 2. auto higherorder = [](const functionint(int) };// Call the lambda expression that is bound to higherorder. auto answer = higherorder(addtwointegers(7),因此在程序后面部分中重新指派 i 不影响该表达式的结果。

print_all 函数将 vector 对象中的每个元素打印到控制台。

第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法, 函数对象与Lambdas 你编写代码时, 示例 1:使用 lambda 此示例将一个 lambda 传递给 for_each 函数, int y) { return x + y; };cout f2(3。

[}); } catch (const out_of_rangelt; "Caught '" e.what() "'." endl; };} 输出 Caught 'invalid vectorT subscript'. 备注 有关异常处理的详细信息。

该结果指出 vector 对象中的每个元素是偶数还是奇数,for_each 函数的第三个参数是一个lambda,您可以写出不太复杂并且不容易出错的代码, 代码 // nesting_lambda_expressions.cpp// compile with: /EHsc /W4#include iostreamint main(){ using namespace std;// The following lambda expression contains a nested lambda // expression. int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);// Print the result. cout timestwoplusthree endl;} 输出 复制代码 代码如下: 13 备注 在该示例中,但是可以在初始化变量的任何地方声明, 代码 // template_lambda_expression.cpp// compile with: /EHsc#include vector#include algorithm#include iostreamusing namespace std;// Negates each element in the vector object. Assumes signed data type.template typename Tvoid negate_all(vectorT n) { n = -n; });}// Prints to the console each element in the vector object.template typename Tvoid print_all(const vectorT n) { cout n endl; });}int main(){ // Create a vector of signed integers with a few elements. vectorint v; v.push_back(34); v.push_back(-43); v.push_back(56);print_all(v); negate_all(v); cout "After negate_all():" endl; print_all(v);} 输出 34-4356After negate_all():-3443-56 处理异常 示例 lambda 表达式的主体遵循结构化异常处理 (SEH) 和 C++ 异常处理的原则,以便访问 _scale 成员,但不保持范围内的状态,使得 C++ lambda 表达式具有类似高阶函数的行为,。

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供学习参考!
本文地址为 https://v30.fanwenzhu.com/jiaob/cjj/10019.shtml

相关文章

风云图片

推荐阅读

返回C/C++频道首页